package org.domeos.framework.shiro.filter;

import java.net.URLDecoder;

import javax.servlet.Filter;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.PathMatchingFilter;
import org.domeos.framework.api.model.auth.User;
import org.domeos.framework.api.service.auth.UserService;
import org.springframework.core.annotation.Order;

import com.gome.idcenter.util.tool.ObjectJsonTranslator;
import com.gome.idcenter.util.vo.CookieVo;

@WebFilter(urlPatterns = "/loginIn/index", filterName = "userCreateFilter")
@Order(1)
public class UserCreateFilter extends PathMatchingFilter implements Filter{
	UserService userService;
	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	@Override
	protected boolean preHandle(ServletRequest servletRequest, ServletResponse response) throws Exception {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		Subject subject = SecurityUtils.getSubject();
		if (subject.getPrincipals() == null) {
			Cookie[] cookies = request.getCookies();
			if (cookies == null) {
			}
			String cookieName = "IDCENTER";
			for (Cookie cookie : cookies) {
				if (cookie.getName().equals(cookieName)) {
					if (cookie.getValue() != null) {
						String cookieVoJsonEncrypt = null;
						try {
							// 判断用户是否登录
							cookieVoJsonEncrypt  = URLDecoder.decode(cookie.getValue(), "UTF-8");
							CookieVo cookieVo = ObjectJsonTranslator.fromString(cookieVoJsonEncrypt, CookieVo.class);
							User user=userService.getUser(cookieVo.getName());
							if(user==null){
								user = new User(cookieVo.getName(), "11111111");
								user.setEmail(cookieVo.getName()+ "@gomeplus.com");
								userService.createUser(user,false);
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
					break;
				}
			}
		}
		return super.preHandle(request, response);
	}
	
}
